package com.remoter.transport.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.io.ByteArrayOutputStream;

import com.remoter.api.serialize.ISerialization;

public class MessageEncoder extends MessageToByteEncoder<Object>{
	
	private ISerialization serialization;
	public MessageEncoder(ISerialization serialization){
		this.serialization = serialization;
	}
	
	@Override
	protected void encode(ChannelHandlerContext ctx,Object msg, ByteBuf out)throws Exception{
		try(ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()){
			this.serialization.serialize(msg,byteArrayOutputStream);
			byte[] body = byteArrayOutputStream.toByteArray();
			int dataLength = body.length;
	        out.writeInt(dataLength);
	        out.writeBytes(body);
		}
	}
	
}